package com.huanglejing.shanggou.common;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.sqlite.SQLiteDatabase;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.multidex.MultiDex;
import android.support.multidex.MultiDexApplication;
import android.text.TextUtils;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.huanglejing.mylibrary.KLog;
import com.huanglejing.shanggou.BuildConfig;
import com.huanglejing.shanggou.greendao.DaoMaster;
import com.huanglejing.shanggou.greendao.DaoSession;
import com.huanglejing.shanggou.utils.C;
import com.huanglejing.shanggou.utils.CacheLoader;
import com.squareup.leakcanary.LeakCanary;
import com.squareup.leakcanary.RefWatcher;
import com.umeng.analytics.MobclickAgent;
import com.umeng.commonsdk.UMConfigure;
import com.umeng.socialize.PlatformConfig;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Method;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Locale;

import rx.plugins.RxJavaErrorHandler;
import rx.plugins.RxJavaPlugins;


/**
 * Created by Administrator on 2016/7/21 0021.
 */
public class AppContext extends MultiDexApplication {
    public static Activity nowActivity;
    private static AppContext instance;
    private static Gson gson;
    private String companyId = "";

    private DaoMaster.DevOpenHelper mHelper;
    private SQLiteDatabase db;
    private DaoMaster mDaoMaster;
    private DaoSession mDaoSession;
    private RefWatcher refWatcher;

    public String getCompanyId() {
        if (!TextUtils.isEmpty(companyId)){
            return companyId;
        }
        if (TextUtils.isEmpty(companyId) && !TextUtils.isEmpty(CacheLoader.getAcache().getAsString(C.Cache.COMPANY_ID))) {
            companyId = CacheLoader.getAcache().getAsString(C.Cache.COMPANY_ID);
            return companyId;
        }
        return companyId;
    }

    public void setCompanyId(String companyId) {
        CacheLoader.getAcache().put(C.Cache.COMPANY_ID, companyId);
        this.companyId = companyId;
    }

    //密钥
    public static String SECRET_KEY = "secret key";

    public static AppContext get() {
        return instance;
    }

    public static Gson gson() {
        if (gson == null) {
            gson = new GsonBuilder().serializeNulls().disableHtmlEscaping().create();
        }
        return gson;
    }


//    public static Account account() {
//        if (!account.isLogin()) {
//            //崩溃后或者account被可能的回收后可以重新获取
//            Account acc = ((Account) CacheLoader.getAcache().getAsObject(C.Account.LOGIN_ACCOUNT));
//            if (acc != null) {
//                account = acc;
//            }
//
//        }
//        return account;
//    }
//
//    public static void setAccount(Account account) {
//        CacheLoader.getAcache().put(C.Account.LOGIN_ACCOUNT, account);
//        AppContext.account = account;
//    }

    public static RefWatcher getRefWatcher(Context context) {
        AppContext application = (AppContext) context.getApplicationContext();
        return application.refWatcher;
    }

    public static String sHA1(Context context) {
        try {
            PackageInfo info = context.getPackageManager().getPackageInfo(
                    context.getPackageName(), PackageManager.GET_SIGNATURES);

            byte[] cert = info.signatures[0].toByteArray();
            MessageDigest md = MessageDigest.getInstance("SHA1");
            byte[] publicKey = md.digest(cert);
            StringBuffer hexString = new StringBuffer();
            for (int i = 0; i < publicKey.length; i++) {
                String appendString = Integer.toHexString(0xFF & publicKey[i])
                        .toUpperCase(Locale.US);
                if (appendString.length() == 1)
                    hexString.append("0");
                hexString.append(appendString);
                hexString.append(":");
            }
            String result = hexString.toString();
            return result.substring(0, result.length() - 1);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static boolean checkPermission(Context context, String permission) {
        boolean result = false;
        if (Build.VERSION.SDK_INT >= 23) {
            try {
                Class<?> clazz = Class.forName("android.content.Context");
                Method method = clazz.getMethod("checkSelfPermission", String.class);
                int rest = (Integer) method.invoke(context, permission);
                if (rest == PackageManager.PERMISSION_GRANTED) {
                    result = true;
                } else {
                    result = false;
                }
            } catch (Exception e) {
                result = false;
            }
        } else {
            PackageManager pm = context.getPackageManager();
            if (pm.checkPermission(permission, context.getPackageName()) == PackageManager.PERMISSION_GRANTED) {
                result = true;
            }
        }
        return result;
    }

    public static String getDeviceInfo(Context context) {
        try {
            org.json.JSONObject json = new org.json.JSONObject();
            android.telephony.TelephonyManager tm = (android.telephony.TelephonyManager) context
                    .getSystemService(Context.TELEPHONY_SERVICE);
            String device_id = null;
            if (checkPermission(context, Manifest.permission.READ_PHONE_STATE)) {
                device_id = tm.getDeviceId();
            }
            String mac = null;
            FileReader fstream = null;
            try {
                fstream = new FileReader("/sys/class/net/wlan0/address");
            } catch (FileNotFoundException e) {
                fstream = new FileReader("/sys/class/net/eth0/address");
            }
            BufferedReader in = null;
            if (fstream != null) {
                try {
                    in = new BufferedReader(fstream, 1024);
                    mac = in.readLine();
                } catch (IOException e) {
                } finally {
                    if (fstream != null) {
                        try {
                            fstream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (in != null) {
                        try {
                            in.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
            json.put("mac", mac);
            if (TextUtils.isEmpty(device_id)) {
                device_id = mac;
            }
            if (TextUtils.isEmpty(device_id)) {
                device_id = android.provider.Settings.Secure.getString(context.getContentResolver(),
                        android.provider.Settings.Secure.ANDROID_ID);
            }
            json.put("device_id", device_id);
            return json.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            MultiDex.install(this);
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
        // SECRET_KEY = AESUtils.generateSecretKey();
        this.registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {

            @Override
            public void onActivityStopped(Activity activity) {
                KLog.d(activity.getClass().getSimpleName(), "onActivityStopped");
            }

            @Override
            public void onActivityStarted(Activity activity) {
                KLog.d(activity.getClass().getSimpleName(), "onActivityStarted");
            }

            @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
                KLog.d(activity.getClass().getSimpleName(), "onActivitySaveInstanceState");
            }

            @Override
            public void onActivityResumed(Activity activity) {
                nowActivity = activity;
                KLog.d(activity.getClass().getSimpleName(), "onActivityResumed  " + nowActivity);
            }

            @Override
            public void onActivityPaused(Activity activity) {
                KLog.d(activity.getClass().getSimpleName(), "onActivityPaused");
            }

            @Override
            public void onActivityDestroyed(Activity activity) {
                nowActivity = null;
                KLog.d(activity.getClass().getSimpleName(), "onActivityDestroyed");
            }

            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
                KLog.d(activity.getClass().getSimpleName(), "onActivityCreated");
            }
        });
        ConfigInit();
        setDatabase();
        try {
            Bundle metaData = this.getPackageManager().getApplicationInfo(getPackageName(), PackageManager.GET_META_DATA).metaData;
            String[] weiXin = metaData.getString("WeChat").split("#");
            String[] qqZone = metaData.getString("QQZone").split("#");
            // String[] qqAppId = metaData.getString("QQAppId").split("#");
            KLog.d("weiXin","weiXin  "+weiXin[0]+"  weiXin   "+weiXin[1]);
            KLog.d("qqZone","qqZone  "+qqZone[0]+"  qqZone   "+qqZone[1]);
            PlatformConfig.setWeixin(weiXin[0], weiXin[1]);
            PlatformConfig.setQQZone(qqZone[0], qqZone[1]);

//
            UMConfigure.init(this, metaData.getString("UMENG_APPKEY"), "umeng", UMConfigure.DEVICE_TYPE_PHONE, "");//58edcfeb310c93091c000be2 5965ee00
            MobclickAgent.startWithConfigure(new MobclickAgent.UMAnalyticsConfig(this, metaData.getString("UMENG_APPKEY"),
                    metaData.getString("UMENG_CHANNEL"), MobclickAgent.EScenarioType.E_UM_NORMAL));

        } catch (Exception e) {
            e.printStackTrace();
        }

        RxJavaPlugins.getInstance().registerErrorHandler(new RxJavaErrorHandler() {
            @Override
            public void handleError(Throwable e) {
                e.printStackTrace();
                // KLog.e(e);
                if (AppContext.get() != null && e != null) {
                    MobclickAgent.reportError(AppContext.get(), e);
                }

            }
        });

    }

    /**
     * 设置greenDao
     */
    private void setDatabase() {
        // 通过 DaoMaster 的内部类 DevOpenHelper，你可以得到一个便利的 SQLiteOpenHelper 对象。
        // 可能你已经注意到了，你并不需要去编写「CREATE TABLE」这样的 SQL 语句，因为 greenDAO 已经帮你做了。
        // 注意：默认的 DaoMaster.DevOpenHelper 会在数据库升级时，删除所有的表，意味着这将导致数据的丢失。
        // 所以，在正式的项目中，你还应该做一层封装，来实现数据库的安全升级。
        // 此处sport-db表示数据库名称 可以任意填写
        mHelper = new DaoMaster.DevOpenHelper(this, "shanggou.db", null);
        db = mHelper.getWritableDatabase();
        // 注意：该数据库连接属于 DaoMaster，所以多个 Session 指的是相同的数据库连接。
        mDaoMaster = new DaoMaster(db);
        mDaoSession = mDaoMaster.newSession();
    }

    public DaoSession getDaoSession() {
        return mDaoSession;
    }

    public SQLiteDatabase getDb() {
        return db;
    }

    private void ConfigInit() {
        if (LeakCanary.isInAnalyzerProcess(this)) {
            // This process is dedicated to LeakCanary for heap analysis.
            // You should not init your app in this process.

        } else {
            refWatcher = LeakCanary.install(this);
        }

        //  BlockCanary.install(this, new AppBlockCanaryContext()).start();
        KLog.init(BuildConfig.DEBUG, "shanggou");  //log // FIXME: 2016/11/2 0002
        if (BuildConfig.DEBUG) {
            //   KLog.d("package:   = " + PackageHelper.getPackageName() + "," + PackageHelper.getPackageInfo());
            //   KLog.d("getChannelName  = " + AnalyticsConfig.getChannel(context));
            KLog.d("sha1  = " + sHA1(this));
            KLog.d("deviceInfo  = " + getDeviceInfo(this));

            StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectAll().penaltyLog().build());
            StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectAll().penaltyLog().build());
        } else {
            KLog.init(BuildConfig.API_Log, "shanggou");  //log // FIXME: 2016/11/2 0002
        }
        //   KLog.d("base url ; " + C.API.CFZX_BASE_HOST);


    }


}
